<template>
  <div class="container">
    <h1>Markdown to Word 转换器</h1>
    
    <div class="instructions">
      <h3>使用说明</h3>
      <ul>
        <li>方式一：点击文件上传区域，选择本地的Markdown文件</li>
        <li>方式二：在文本输入框中直接粘贴Markdown内容</li>
        <li>点击"转换"按钮，系统会将Markdown转换为Word文档</li>
        <li>转换完成后，点击"下载Word文件"按钮获取转换后的文档</li>
      </ul>
    </div>
    
    <div :id="'status'" :class="['status', statusType]"></div>
    
    <div class="input-methods-container">
      <div class="input-section">
        <div class="section-title">方式一：上传Markdown文件</div>
        <div 
          class="file-upload" 
          id="fileUploadArea"
          @dragover.prevent="handleDragOver"
          @dragleave="handleDragLeave"
          @drop.prevent="handleDrop"
        >
          <input 
            type="file" 
            id="fileInput" 
            accept=".md,.markdown"
            @change="handleFileChange"
          >
          <label for="fileInput" class="file-upload-label">
            点击或拖拽文件到此处上传
          </label>
          <div id="fileInfo" class="file-info">{{ fileInfoText }}</div>
        </div>
      </div>
      
      <div class="input-section">
        <div class="section-title">方式二：粘贴Markdown文本</div>
        <textarea 
          class="text-input" 
          id="markdownInput" 
          placeholder="在此粘贴Markdown文本内容..."
          v-model="markdownText"
        ></textarea>
      </div>
    </div>
    
    <div class="buttons">
      <button class="btn btn-primary" id="convertBtn" @click="convertToWord">转换为Word</button>
      <button class="btn btn-secondary" id="clearBtn" @click="clearAll">清空</button>
    </div>
  </div>
  
  <!-- 固定在底部的下载条 -->
  <div class="download-bar" id="downloadBar" v-show="showDownloadSection">
    <div class="container">
      <div class="download-bar-content">
        <div class="download-info">
          <h3>转换完成！</h3>
          <p>点击下方按钮下载转换后的Word文档</p>
        </div>
        <a href="#" class="btn btn-primary btn-large" id="downloadBtn" @click.prevent="downloadWord">下载Word文件</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { saveAs } from 'file-saver';
import { MarkdownToIntermediateConverter, IntermediateToWordConverter } from './DocumentConverter';

// 响应式数据
// 设置一个简单的默认Markdown内容
const markdownText = ref('# 测试文档\n\n这是一个用于测试的简单Markdown文档。\n\n## 二级标题\n\n- 项目1\n- 项目2\n\n这是一段普通文本。');
const fileInfoText = ref('未选择文件');
const showDownloadSection = ref(false);
const statusType = ref('');
let wordBlob: Blob | null = null;
let originalFileName = ref('');

/**
 * 处理文件选择变化
 * @param event 文件选择事件
 */
function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    fileInfoText.value = `已选择文件：${file.name}`;
    originalFileName.value = file.name;
    
    // 读取文件内容
    const reader = new FileReader();
    reader.onload = (event) => {
      markdownText.value = event.target?.result as string;
    };
    reader.readAsText(file);
  } else {
    fileInfoText.value = '未选择文件';
    originalFileName.value = '';
  }
}

/**
 * 处理拖拽悬停
 */
function handleDragOver() {
  const fileUploadArea = document.getElementById('fileUploadArea');
  if (fileUploadArea) {
    fileUploadArea.classList.add('dragover');
  }
}

/**
 * 处理拖拽离开
 */
function handleDragLeave() {
  const fileUploadArea = document.getElementById('fileUploadArea');
  if (fileUploadArea) {
    fileUploadArea.classList.remove('dragover');
  }
}

/**
 * 处理文件拖拽放置
 * @param event 拖拽事件
 */
function handleDrop(event: DragEvent) {
  const fileUploadArea = document.getElementById('fileUploadArea');
  if (fileUploadArea) {
    fileUploadArea.classList.remove('dragover');
  }
  
  if (event.dataTransfer && event.dataTransfer.files.length > 0) {
    const file = event.dataTransfer.files[0];
    if (file.type === 'text/markdown' || file.name.endsWith('.md') || file.name.endsWith('.markdown')) {
      const fileInput = document.getElementById('fileInput') as HTMLInputElement;
      if (fileInput) {
        // 使用DataTransfer API设置文件
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        fileInput.files = dataTransfer.files;
      }
      
      fileInfoText.value = `已选择文件：${file.name}`;
      originalFileName.value = file.name;
      
      // 读取文件内容
      const reader = new FileReader();
      reader.onload = (event) => {
        markdownText.value = event.target?.result as string;
      };
      reader.readAsText(file);
    } else {
      showStatus('请上传Markdown格式的文件', 'error');
    }
  }
}

/**
 * 将Markdown转换为Word文档
 */
async function convertToWord() {
  if (!markdownText.value.trim()) {
    showStatus('请输入或上传Markdown内容', 'error');
    return;
  }
  
  showStatus('正在转换，请稍候...', 'success');
  
  try {
    console.log('开始Markdown到中间文档格式的转换...');
    
    // 1. 创建转换器实例
    const mdToIntermediateConverter = new MarkdownToIntermediateConverter();
    const intermediateToWordConverter = new IntermediateToWordConverter();
    
    // 2. 将Markdown转换为中间文档格式
    const intermediateDoc = mdToIntermediateConverter.convert(markdownText.value);
    console.log('中间文档格式转换完成，元素数量:', intermediateDoc?.content?.length || 0);
    
    // 检查中间文档是否有效
    if (!intermediateDoc || !intermediateDoc.content || intermediateDoc.content.length === 0) {
      throw new Error('中间文档格式无效或内容为空');
    }
    
    // 3. 将中间文档格式转换为Word文档Blob
    console.log('开始中间文档格式到Word的转换...');
    wordBlob = await intermediateToWordConverter.convert(intermediateDoc);
    
    // 检查生成的Word Blob是否有效
    if (!wordBlob || wordBlob.size === 0) {
      throw new Error('生成的Word文档为空');
    }
    
    console.log('文档Blob大小:', wordBlob.size);
    console.log('wordBlob赋值成功:', wordBlob !== null);
    
    // 使用nextTick确保UI更新
    await nextTick();
    
    // 显示下载区域
    console.log('设置showDownloadSection.value为true');
    showDownloadSection.value = true;
    console.log('showDownloadSection当前值:', showDownloadSection.value);
    
    // 显示成功状态，但不自动隐藏，以便用户能够看到下载选项
    showStatus('转换成功！请点击下方按钮下载Word文档', 'success');
    
  } catch (error) {
    console.error('转换错误:', error);
    showDownloadSection.value = false;
    // 显示更详细的错误信息
    if (error instanceof Error) {
      showStatus(`转换失败: ${error.message}`, 'error');
    } else {
      showStatus('转换失败，请稍后重试', 'error');
    }
  }
}

/**
 * 下载Word文件
 */
function downloadWord() {
  if (wordBlob) {
    // 生成文件名：如果有原始文件名，则使用原始文件名但修改扩展名为.docx
    // 否则使用默认名称
    let fileName = 'markdown_to_word.docx';
    if (originalFileName.value) {
      // 移除原始扩展名，添加.docx
      const nameWithoutExt = originalFileName.value.substring(0, originalFileName.value.lastIndexOf('.')) || originalFileName.value;
      fileName = nameWithoutExt + '.docx';
    }
    
    saveAs(wordBlob, fileName);
  }
}

/**
 * 清空所有输入和状态
 */
function clearAll() {
  const fileInput = document.getElementById('fileInput') as HTMLInputElement;
  if (fileInput) {
    fileInput.value = '';
  }
  fileInfoText.value = '未选择文件';
  markdownText.value = '';
  showDownloadSection.value = false;
  statusType.value = '';
  const status = document.getElementById('status');
  if (status) {
    status.textContent = '';
    status.style.display = 'none';
  }
}

/**
 * 显示状态信息
 * @param message 状态消息
 * @param type 状态类型（success或error）
 */
function showStatus(message: string, type: string) {
  const status = document.getElementById('status');
  if (status) {
    status.textContent = message;
    status.style.display = 'block';
    statusType.value = `status-${type}`;
    
    // 3秒后自动隐藏成功状态，但保留转换成功消息
    if (type === 'success' && message !== '正在转换，请稍候...' && message !== '转换成功！请点击下方按钮下载Word文档') {
      setTimeout(() => {
        status.style.display = 'none';
        statusType.value = '';
      }, 3000);
    }
  }
}
</script>

<style scoped>
/* 组件特定样式可以在这里定义 */
.file-upload.dragover {
  background-color: #e3f2fd;
  border-color: #1976d2;
}
</style>